package com.bc.bccore.common;

import com.bc.commoncore.util.CookieUtils;
import com.bc.commoncore.util.SpringBeanHelper;
import com.bc.bccore.redis.RedisService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created by zhuzh on 2018/4/10.
 */
public class LoginHelper {
    private final static RedisService redisService;
    static {
        redisService = SpringBeanHelper.getCustomBeanByType(RedisService.class);
    }



    /**
     * 存储验证码到redis中
     *
     * @author zhuzh
     * @param code
     */
    public static void storeAuthCode2Redis(String code , String cookieKey, HttpServletRequest request, HttpServletResponse response) {
        String redisKey = UUID.randomUUID().toString();
        redisService.set(redisKey, code,5 * 60);
        CookieUtils.setCookie(request, response,cookieKey, redisKey, 5 * 60);
    }

    /**
     * 获取验证码
     *
     * @param request
     * @author zhuzh
     * @return
     */
    public static String getAuthCode(HttpServletRequest request, String cookieKey) {
        String codeCookie = CookieUtils.getCookie(request, cookieKey);
        if (codeCookie != null) {
            return redisService.get(codeCookie);
        }
        return null;
    }

    /**
     * 删除验证码的cookie
     * @param request
     * @param response
     */
    public static void removeAuthCodeCookie(HttpServletRequest request, HttpServletResponse response, String cookieKey) {
        CookieUtils.deleteCookie(request, response, cookieKey);
    }
}
